import i18n from '@/i18n/index'

/**
 * @description 扁平化处理字典数据为对象
 * @param {*} dictList
 * @return {*}
 */
export const getFlattenDictData = (dictList) => {
  let dictObj = {}
  for (let i = 0, len = dictList.length; i < len; i++) {
    const catRoute = dictList[i].catRoute
    let childList = dictList[i].children
    dictObj[catRoute] = {
      ...dictList[i],
      children: []
    }
    if (childList && childList.length) {
      // 只复制最邻近的子数据
      childList = JSON.parse(JSON.stringify(childList)).map((item) => {
        // item.children = []
        return item
      })
      dictObj[catRoute].children = childList
      const obj = getFlattenDictData(dictList[i].children)
      dictObj = {
        ...dictObj,
        ...obj
      }
    }
  }
  return dictObj
}

/**
 * @description 多语言的兼容处理
 * @param {*} data
 * @returns
 */
export const langCompatible = (key, label = '') => {
  if (key === 'null' || key === 'undefined') return ''
  let t = i18n.global.t(key)
  for (const param in label) {
    t = t.replace(`{${param}}`, label[param])
  }
  return t === key || !t ? label || getDictDesc(key) || key : t
}

/**
 * @description 挂载全局的多语言获取对应的文本
 * @export
 * @param {*} catRoute
 * @return {*}
 */
export const getDictDesc = (catRoute) => {
  if (window.flattenDictData && window.flattenDictData[catRoute]) {
    const catDesc = window.flattenDictData[catRoute]?.catDesc
    return catDesc || ''
  }
  return ''
}
